package cn.bugstack.mybatis.bindings;

import cn.bugstack.mybatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MapperProxy<T> implements InvocationHandler {

    private SqlSession sqlSession;
    private Class<T> mapperInterface;


    private Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<>();

    public MapperProxy(Class<T> mapperInterface, SqlSession sqlSession) {
        this.mapperInterface = mapperInterface;
        this.sqlSession = sqlSession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getDeclaringClass().equals(Object.class)) {
            return method.invoke(this, args);
        }
        // 缓存方法
        if (!methodCache.containsKey(method)) {
            methodCache.put(method, new MapperMethod(sqlSession.getConfiguration(), mapperInterface, method));
        }
        return methodCache.get(method).execute(sqlSession, args);

    }
}
